package com.gqj.meter.controller;

import com.alibaba.fastjson.JSON;
import com.gqj.common.annotation.Log;
import com.gqj.common.constant.UserConstants;
import com.gqj.common.core.controller.BaseController;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.core.page.TableDataInfo;
import com.gqj.common.enums.BusinessType;
import com.gqj.common.utils.StorageUtil;
import com.gqj.common.utils.poi.ExcelUtil;
import com.gqj.meter.domain.MdInTaskDetails;
import com.gqj.meter.domain.MdIt;
import com.gqj.meter.domain.vo.MdItVo;
import com.gqj.meter.mapper.MdInTaskDetailsMapper;
import com.gqj.meter.service.IMdItService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 互感器Controller
 *
 * @author lxq
 * @date lxq-02-10
 */
@Api(value = "/meter/mdIt", description = "互感器")
@RestController
@RequestMapping("/meter/mdIt")
public class MdItController extends BaseController {
    @Autowired
    private IMdItService mdItService;
    @Value("${downloadPath}")
    private String downloadPath;
    @Autowired
    private MdInTaskDetailsMapper mdInTaskDetailsMapper;

    /**
     * 查询互感器列表
     */
    @ApiOperation("查询互感器列表")
    @PreAuthorize("@ss.hasPermi('meter:mdIt:list')")
    @GetMapping("/list")
    public TableDataInfo list(MdIt mdIt) {
        startPage();
        List<MdIt> list = mdItService.selectMdItList(mdIt);
        return getDataTable(list);
    }

    /**
     * 导出互感器列表
     */
    @ApiOperation("导出互感器列表")
    @PreAuthorize("@ss.hasPermi('meter:mdIt:export')")
    @Log(title = "互感器", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MdIt mdIt) {
        List<MdIt> list = mdItService.selectMdItList(mdIt);
        ExcelUtil<MdIt> util = new ExcelUtil<MdIt>(MdIt.class);
        util.exportExcel(response, list, "互感器数据");
    }

    /**
     * 获取互感器详细信息
     */
    @ApiOperation("获取互感器详细信息")
    @PreAuthorize("@ss.hasPermi('meter:mdIt:query')")
    @GetMapping(value = "/{itId}")
    public AjaxResult getInfo(@PathVariable("itId") Long itId) {
        return success(mdItService.selectMdItByItId(itId));
    }

    /**
     * 新增互感器
     */
    @ApiOperation("新增互感器")
    @PreAuthorize("@ss.hasPermi('meter:mdIt:add')")
    @Log(title = "互感器", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MdIt mdIt) {
        if (UserConstants.NOT_UNIQUE.equals(mdItService.checkRfidNoUnique(mdIt))) {
            return AjaxResult.error("新增'" + mdIt.getRfidNo() + "'失败，条形码已存在！");
        }
        return toAjax(mdItService.insertMdIt(mdIt));
    }

    /**
     * 修改互感器
     */
    @ApiOperation("修改互感器")
    @PreAuthorize("@ss.hasPermi('meter:mdIt:edit')")
    @Log(title = "互感器", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MdIt mdIt) {
        if (null == mdIt.getItId() || 0 == mdIt.getItId()) {
            return AjaxResult.error("修改失败，互感器ID为空！");
        }
        if (UserConstants.NOT_UNIQUE.equals(mdItService.checkRfidNoUnique(mdIt))) {
            return AjaxResult.error("修改'" + mdIt.getRfidNo() + "'失败，条形码已存在！");
        }
        return toAjax(mdItService.updateMdIt(mdIt));
    }

    /**
     * 删除互感器
     */
    @ApiOperation("删除互感器")
    @PreAuthorize("@ss.hasPermi('meter:mdIt:remove')")
    @Log(title = "互感器", businessType = BusinessType.DELETE)
    @DeleteMapping("/{itIds}")
    public AjaxResult remove(@PathVariable Long[] itIds) {
        //判断互感器是否被引用
        for (int i = 0; i < itIds.length; i++) {
            MdIt mdIt = mdItService.selectMdItByItId(itIds[i]);

            String serviceStatus = mdIt.getServiceStatus();
            if (!"00".equals(serviceStatus) && !"01".equals(serviceStatus) && !"04".equals(serviceStatus)) {
                return AjaxResult.error("互感器" + mdIt.getRfidNo() + "的业务状态不允许删除！");
            }

            //查看出入库是否引用
            MdInTaskDetails mdInTaskDetails = new MdInTaskDetails();
            mdInTaskDetails.setRfidNo(mdIt.getRfidNo());
            mdInTaskDetails.setIsComplete("0");
            List<MdInTaskDetails> mdInTaskDetailsList = mdInTaskDetailsMapper.selectMdInTaskDetailsList(mdInTaskDetails);
            if (mdInTaskDetailsList.size() > 0) {
                return AjaxResult.error("互感器" + mdIt.getRfidNo() + "入库任务中已经引用，无法删除！");
            }
        }
        return toAjax(mdItService.deleteMdItByItIds(itIds));
    }

    /**
     * 下载互感器json文件
     */
    @ApiOperation("下载互感器json文件")
    @PreAuthorize("@ss.hasPermi('meter:mdIt:downloadJsonMdIt')")
    @GetMapping("/downloadJsonMdIt")
    public AjaxResult downloadJsonMdIt(MdIt mdIt) {
        List<MdIt> mt = mdItService.selectMdItList(mdIt);
        List<MdItVo> vos = StorageUtil.copyList(mt, MdItVo::new);

        String orderNo = StorageUtil.getOrderNoTo12();
        // 生成文件名
        String fileName = downloadPath;
        String jsonStringAc = JSON.toJSONString(vos);
        StorageUtil.createJsonFile(jsonStringAc, fileName, "互感器数据" + orderNo);
        return AjaxResult.success(fileName + "互感器数据" + orderNo);
    }

    /**
     * 导入互感器execl文件
     */
    @ApiOperation("导入互感器execl文件")
    @Log(title = "导入互感器execl文件", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('meter:mdIt:importDataIt')")
    @PostMapping("/importDataIt")
    public AjaxResult importDataIt(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<MdIt> util = new ExcelUtil<MdIt>(MdIt.class);
        List<MdIt> mdItList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = mdItService.importId(mdItList, updateSupport, operName);
        return success(message);
    }

    @ApiOperation("下载互感器模板")
    @PostMapping("/importTemplateMdIt")
    @PreAuthorize("@ss.hasPermi('meter:mdIt:importTemplateMdIt')")
    public void importTemplateMdIt(HttpServletResponse response) {
        ExcelUtil<MdIt> util = new ExcelUtil<MdIt>(MdIt.class);
        util.importTemplateExcel(response, "互感器数据");
    }
}
